package com.loveprogrammer.eternity.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.loveprogrammer.eternity.enums.QualityEnum;
import com.loveprogrammer.eternity.enums.SkillQualityEnum;
import com.loveprogrammer.eternity.factory.*;
import com.loveprogrammer.eternity.model.Hero;
import com.loveprogrammer.eternity.model.Monster;
import com.loveprogrammer.eternity.model.effect.AbstractEffect;
import com.loveprogrammer.eternity.model.effect.Effect;
import com.loveprogrammer.eternity.model.game.GameWrapper;
import com.loveprogrammer.eternity.model.game.HeroWrapper;
import com.loveprogrammer.eternity.model.game.PetWrapper;
import com.loveprogrammer.eternity.model.game.TaskManager;
import com.loveprogrammer.eternity.model.mission.MissionDefinition;
import com.loveprogrammer.eternity.model.product.Equipment;
import com.loveprogrammer.eternity.model.product.Goods;
import com.loveprogrammer.eternity.model.product.equipment.Equips;
import com.loveprogrammer.eternity.model.task.TaskDefinition;
import com.loveprogrammer.eternity.skill.Skill;
import com.loveprogrammer.eternity.skill.State;
import com.loveprogrammer.eternity.skill.support.skills.AbstractSkill;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0.0
 * @description:
 * @author: eric
 * @date: 2022-08-19 16:39
 **/
public class LoadGame {

    public static GameWrapper load() throws IOException, ClassNotFoundException {
        GameWrapper gameWrapper = new GameWrapper();
        Map<String,HeroWrapper> heroWrapperMap = new HashMap<>();

        File file = new File("save");
        if(file.isDirectory()){
            File[] files = file.listFiles();
            // 公共装备
            String commonBuffer = Util.readFileContentAsBuffer("save/commonEquipments.json");
            if(!"".equals(commonBuffer)) {
                CommonEquipmentFactory.init(commonBuffer);
            }
            for (File saveFile : files) {
                if(!saveFile.isDirectory()){
                    continue;
                }
                System.out.println(saveFile.getPath());
                String buffer = Util.readFileContentAsBuffer(saveFile.getPath() + "/save.json");

                JSONObject jsonObject = JSONObject.parseObject(buffer);
                Integer currentExp = jsonObject.getJSONObject("hero").getInteger("currentExp");

                HeroWrapper heroWrapper = JSON.parseObject(buffer, HeroWrapper.class);
                TaskManager taskManager = heroWrapper.getTaskManager();

                JSONObject taskM = jsonObject.getJSONObject("taskManager");
                if(taskM != null) {
                    JSONArray allTasks = taskM.getJSONArray("allTasks");
                    if(allTasks != null && !allTasks.isEmpty()) {
                        List<TaskDefinition> all = new ArrayList<>();
                        for (Object allTask : allTasks) {
                            JSONObject object = (JSONObject) allTask;
                            TaskDefinition taskDefinition = JSON.parseObject(object.toJSONString(), TaskDefinition.class);
                            JSONObject mission = object.getJSONObject("mission");
                            String missionClass = object.getString("missionClass");
                            Class<?> aClass = Class.forName(missionClass);
                            MissionDefinition missionDefinition = (MissionDefinition) JSON.parseObject(mission.toJSONString(), aClass);
                            taskDefinition.setMission(missionDefinition);
                            all.add(taskDefinition);
                        }
                        taskManager.setAllTasks(all);
                    }
                }

                // HeroWrapper heroWrapper = gameWrapper.getHeroWrapperMap().get("eric");
                Hero hero = heroWrapper.getHero();
                hero.setCurrentExp(currentExp);

                String equipJson = Util.readFileContentAsBuffer(saveFile.getPath() + "/equips.json");
                Equips equips = JSON.parseObject(equipJson, Equips.class);
                if(equips != null) {
                    equips.initAll();
                    hero.setEquips(equips);
                    List<Goods.GoodsEffectTemplate> effects = equips.checkEffects();
                    if(effects.size() > 0){
                        for (Goods.GoodsEffectTemplate effect : effects) {
                            AbstractEffect effectReal = EffectFactory.getEffectById(effect.getTemplateId());
                            hero.regEffect(effectReal);
                        }
                    }
                }else{
                    hero.setEquips(new Equips());
                }

                String skillsJson = Util.readFileContentAsBuffer(saveFile.getPath() + "/skills.json");
                JSONArray skillArray = JSONArray.parseArray(skillsJson);

                List<Skill> skills = new ArrayList<>();
                for (Object skill : skillArray) {
                    JSONObject sk = (JSONObject) skill;
                    Integer id = sk.getInteger("id");
                    Integer level = sk.getInteger("level");
                    String quality = sk.getString("quality");
                    sk.getInteger("level");
                    Skill newSkill = SkillFactory.getNewSkillById(id, SkillQualityEnum.getByCode(quality));
                    newSkill.setLevel(level);
                    skills.add(newSkill);
                }
                hero.setSkills(skills);

                // 任务更新


                // 更新
                hero.reset();

                // effects


                // 给宠物重新赋予技能
                List<PetWrapper> pets = heroWrapper.getPets();
                for (PetWrapper pet : pets) {
                    Monster monster = pet.getPet();
                    String monsterSkills = monster.getTemplate().getSkills();
                    List<Skill> skillList = new ArrayList<>();
                    if(monsterSkills != null && !"".equals(monsterSkills)){
                        String[] split = monsterSkills.split(",");
                        for (String id : split) {
                            if(MonsterFactory.excludeSkills.contains(id)){
                                continue;
                            }
                            Skill newSkill = SkillFactory.getNewSkillByIdAndMonsterId(id,monster.getTemplate().getId());
                            // TODO 这里要扩展一下 根据野怪的id 技能的威力有所不同
                            if(newSkill == null){
                                System.out.println(id);
                            }else {
                                newSkill.setLevel(1);
                                for (int i = 1; i <= hero.getLevel(); i++) {
                                    newSkill.levelUp(i);
                                }
                                skillList.add(newSkill);
                            }
                        }
                    }
                    monster.setSkills(skillList);

                    String states = monster.getTemplate().getStates();
                    if(states != null && !"".equals(states)){
                        String[] split = states.split(",");
                        List<State> stateList = new ArrayList<>();
                        for (String id : split) {
                            stateList.add(StateFactory.getById(Integer.parseInt(id)));
                        }
                        monster.setStates(stateList);
                    }
                }
                heroWrapper.resetThings();
                heroWrapperMap.put(saveFile.getName(),heroWrapper);
            }
        }
        gameWrapper.setHeroWrapperMap(heroWrapperMap);
        return gameWrapper;
    }

    public static void save(GameWrapper gameWrapper) {
        // System.out.println("auto save game begin");
        // 有几个是要单独保存的 每个英雄保存一个目录 目前是技能、装备
        Map<String, HeroWrapper> map = gameWrapper.getHeroWrapperMap();

        for (Map.Entry<String, HeroWrapper> entry : map.entrySet()) {
            String key = entry.getKey();
            HeroWrapper value = entry.getValue();

            // 创建一个文件夹
            File file = new File("save/" + key);
            file.mkdirs();

            Util.writeIntoFile(JSON.toJSONString(value, SerializerFeature.WriteNonStringKeyAsString), "save/" + key + "/save.json");

            Hero hero = value.getHero();
            List<Skill> skills = hero.getSkills();
            Util.writeIntoFile(JSON.toJSONString(skills), "save/" + key + "/skills.json");

            Equips equips = hero.getEquips();
            Util.writeIntoFile(JSON.toJSONString(equips), "save/" + key + "/equips.json");

            List<Equipment> commonEquipments = CommonEquipmentFactory.getCommonEquipments();
            Util.writeIntoFile(JSON.toJSONString(commonEquipments), "save/commonEquipments.json");
        }
        // System.out.println("auto save game end");
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        GameWrapper load = load();

        System.out.println(JSON.toJSON(load));
    }
}
